package com.yixun.qfbao.filters;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.alibaba.fastjson.JSONObject;
import com.qiaofang.log.context.LogContext;
import com.yixun.qfbao.config.LoginConfig;
import com.yixun.qfbao.constants.ApiConstant;
import com.yixun.qfbao.dto.base.BaseResponseDTO;
import com.yixun.qfbao.model.Company;
import com.yixun.qfbao.model.PartnerInfo;
import com.yixun.qfbao.model.enums.PartnerInfoEnum;
import com.yixun.qfbao.model.enums.SystemIdEnum;
import com.yixun.qfbao.response.CommonResponse;
import com.yixun.qfbao.service.CompanyService;
import com.yixun.qfbao.utils.LoginUtils;
import com.yixun.qfbao.xf.model.enums.ResultEnum;

/**
 * 验证是否已经登录，过滤器
 *
 * @author ThinkPad
 */
//@WebFilter(urlPatterns = {"/api/*", "/agency/*"}, filterName = "loginFilter")
//@EnableConfigurationProperties(LoginConfig.class)
//在springboot启动时，需加上此注解。
//@Configuration
public class LoginFilter implements Filter {

	@Autowired
	private CompanyService companyService;

	@Autowired
	private LoginUtils loginUtils;
	
	private String[] NOT_FILTER_URL = new String[] {
		"/api/getLogo",
		"/api/login",
		"/api/loginExit",
		"/sendValidateCodeForPwd",
		"api/resetPwd",
		"/sendVerificationCode",
		"api/regist",
		"weapp/regist",
		"api/getCompanyByPhone",
		"api/getCompanyByAssistantPhone",
		"/api/getAgencyIndexSwitch",
		"/api/getSharePremisesDetail",
		"/api/js_ticket",
		"/api/sendFailureWxmsgAgain",
		"/api/redisOperate",
		"openapi/getPremises",
		"openapi/getProvince",
		"/weapp/login",
		"/api/newlogin",
		"/init/heiheihei",
		"/agency/weapp/premises/getPremisesDetail",
		"/agency/weapp/premises/getAllImageByPremisesId",
		"/agency/weapp/my/getRegesiterDeptInfo",
		"/agency/weapp/my/getPartnerInfo",
		"/agency/weapp/premises/getAgentPremiseInfoPage",
		"getDepartmentQrCodeUrl",
		"/common/getCommonArea"
	};

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain arg2)
		throws IOException, ServletException {
		BaseResponseDTO<String> baseDto = new BaseResponseDTO<String>();
		baseDto.setResult(ResultEnum.FAIL.getNo());
		baseDto.setResData("errorLogin");
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		res.setContentType("application/json; charset=utf-8");
		String requestURI = req.getRequestURI();

		String userIdStr = req.getHeader("userId");
		String companyUuid = req.getHeader("companyUuid");
		// LogContext 巧房日志平台记录信息
		LogContext.getCurrent().setTraceId(UUID.randomUUID().toString());
		if(StringUtils.isNotBlank(companyUuid)){
			LogContext.getCurrent().setCompanyUUID(companyUuid);
		}
		if(StringUtils.isNotBlank(userIdStr)){
			LogContext.getCurrent().setUserId(userIdStr);
		}
		String loginType = req.getHeader("loginType");
		
		boolean notFilterFlag = false;
		for(int i = 0; i < NOT_FILTER_URL.length; i ++) {
			if(requestURI.indexOf(NOT_FILTER_URL[i]) >= 0) {
				notFilterFlag = true;
				break;
			}
		}
		if (notFilterFlag || requestURI.contains("test") ||(SystemIdEnum.AGENCY_h5.getCode().equals(loginType))) {
			arg2.doFilter(req, res);
		} else if (ApiConstant.OPTIONS.equals(req.getMethod())) {
			// 跨域情况下，浏览器的Header预检查
			arg2.doFilter(req, res);
		} else {
			if (StringUtils.isEmpty(userIdStr) || StringUtils.equals("null", userIdStr)) {
				userIdStr = req.getParameter("params.userId");
			}
			if (StringUtils.isBlank(userIdStr)) {
                res.setHeader("Access-Control-Allow-Origin", "*");
                //如果是分销小程序，使用commonResponse返回
				if(SystemIdEnum.WEAPP_AGENCY.getCode().equals(loginType)) {
					CommonResponse commonResponse = new CommonResponse();
					commonResponse.setCode("-1");
					commonResponse.setMsg("未登录");
					response.getWriter().print(JSONObject.toJSONString(commonResponse));
					return;
				}
				baseDto.setResult("-1");
                response.getWriter().print(JSONObject.toJSONString(baseDto));
				return;
			}
			Long userId = Long.valueOf(userIdStr);
			PartnerInfo partnerInfo = loginUtils.getUser(userId);

//			//后台发布时后端缓存失效，微信端系统自动登录时由于登录校验较多比较慢，导致后去权限时数据异常
//			if(partnerInfo == null) {
//			    partnerInfo = partnerInfoService.selectById(userId);
//            }

			if (null == partnerInfo) {
                res.setHeader("Access-Control-Allow-Origin", "*");
                //如果是分销小程序，使用commonResponse返回
				if(SystemIdEnum.WEAPP_AGENCY.getCode().equals(loginType)) {
					CommonResponse commonResponse = new CommonResponse();
					commonResponse.setCode("-1");
					commonResponse.setMsg("未登录");
					response.getWriter().print(JSONObject.toJSONString(commonResponse));
					return;
				}
				baseDto.setResult(ResultEnum.USER_IS_NULL.getNo());
				response.getWriter().print(JSONObject.toJSONString(baseDto));
				return;
			} else {
				loginUtils.putUser(partnerInfo);
				Company company = companyService.selectById(partnerInfo.getHigherid());
				Long companyType = company.getCompanyType();
				if (SystemIdEnum.ASSISTANT.getCode().equals(partnerInfo.getLoginType())
					|| SystemIdEnum.DEVELOPERS.getCode().equals(partnerInfo.getLoginType())
					|| SystemIdEnum.APP_ASSISTANT.getCode().equals(partnerInfo.getLoginType())) {
					// 案场助手
					if ("1".equals(String.valueOf(companyType))) {
                        res.setHeader("Access-Control-Allow-Origin", "*");
                        baseDto.setResult(ResultEnum.USER_IS_NULL.getNo());
                        response.getWriter().print(JSONObject.toJSONString(baseDto));
						return;
					}
				} else {
					// 中介公司
					// 若为开发商类型，再判断角色类型是否为游客
					if ("20".equals(String.valueOf(companyType))
						&& !PartnerInfoEnum.TOURIST_ROLE.getCode().equals(partnerInfo.getUserRoleId() + "")) {
                        res.setHeader("Access-Control-Allow-Origin", "*");
                        baseDto.setResult(ResultEnum.USER_IS_NULL.getNo());
                        response.getWriter().print(JSONObject.toJSONString(baseDto));
						return;
					}
				}
			}
			arg2.doFilter(req, res);
		}

	}

	/*
	 * 使用autowireCapableBeanFactory在filter初始化时注入bean，否则使用autowired或者resource值为null。 因为filter在servlet之前加载。
	 */
	@Override
	public void init(FilterConfig filterConfig)
		throws ServletException {
		ServletContext servletContext = filterConfig.getServletContext();
		WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		AutowireCapableBeanFactory autowireCapableBeanFactory = webApplicationContext.getAutowireCapableBeanFactory();
		autowireCapableBeanFactory.configureBean(this, "partnerInfoService");
		autowireCapableBeanFactory.configureBean(this, "loginConfig");

	}
//
//	// 检查是否为不需要拦截做登陆验证的url
//	private boolean isExcludedUrl(String url) {
//		String[] excludedUrls = loginConfig.getExcludedUrls();
//		if (excludedUrls == null || excludedUrls.length <= 0) {
//			return false;
//		}
//		for (String ex : excludedUrls) {
//			url = url.trim();
//			ex = ex.trim();
//			if (url.toLowerCase().indexOf(ex.toLowerCase()) >= 0)
//				return true;
//		}
//		return false;
//	}
	
	
	public static void main(String[] args) {
		
		//121.346566, 31.203625
		//121.428923, 31.185338
		//117.175734, 31.848468
		//121.929342,30.892127
		double lat = 30.892127f;
		double lng = 121.929342f;
		

	    float x_pi = 3.14159265358979324f;
	    double x = lng - 0.0065;
	    double y = lat - 0.006;
	    double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
	    double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
	    System.out.println(z * Math.cos(theta) + "," + z * Math.sin(theta));
		
	}
}
